package main

import (
	"go_code/day15/database"
)

// 出版社
type Publisher struct {
	Id   uint
	Name string `gorm:"size:20"`
	Book []Book `gorm:"foreignKey:PublisherId;references:Id;"`
}

func (p Publisher) TableName() string {
	return "publisher"
}

// 图书
type Book struct {
	Id          uint
	Title       string `gorm:"size:20"`
	PublisherId uint
	Publisher   Publisher
}

func (p Book) TableName() string {
	return "book"
}

func main() {
	db := database.DB()
	db.AutoMigrate(&Publisher{}, &Book{})
	// 数据插入
	// pub := Publisher{
	// 	Name: "清华大学出版社",
	// 	Book: []Book{
	// 		{Title: "Golang开发"},
	// 		{Title: "WEB前端开发"},
	// 		{Title: "Python开发"},
	// 	},
	// }
	// db.Create(&pub)
	// fmt.Println("出版社的Id:", pub.Id)

	// pub := Publisher{
	// 	Name: "中信出版社",
	// }
	// db.Create(&pub)
	// fmt.Println("出版社的Id:", pub.Id)

	// book := []Book{
	// 	{Title: "软件测试", PublisherId: 2},
	// 	{Title: "Java开发", PublisherId: 2},
	// }
	// db.Create(&book)

	// 查询
	// var pub Publisher
	// db.Preload("Book").Where("id = ?", 2).First(&pub)
	// fmt.Println(pub)

	// var book Book
	// db.Preload("Publisher").Where("id = ?", 3).First(&book)
	// fmt.Println(book)
	// fmt.Println(book.Title, book.Publisher.Name)

	// 删除
	var pub Publisher
	db.Where("id = ?", 1).First(&pub)
	db.Unscoped().Delete(&pub)
}
